package com.lezijie.seckill.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lezijie.seckill.pojo.Order;
import com.lezijie.seckill.pojo.SeckillOrder;
import com.lezijie.seckill.pojo.User;
import com.lezijie.seckill.service.IGoodsService;
import com.lezijie.seckill.service.IOrderService;
import com.lezijie.seckill.service.ISeckillOrderService;
import com.lezijie.seckill.vo.GoodsVo;
import com.lezijie.seckill.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author 孙志鹏
 * @createDate 2022/1/6 22:22
 */
@Controller
@RequestMapping("/seckill")
public class SeckillController {

    @Autowired
    IGoodsService goodsService;
    @Autowired
    ISeckillOrderService seckillOrderService;
    @Autowired
    IOrderService orderService;

    @PostMapping("/doSeckill")
    public String doSeckill(Model model, User user, Long goodsId) {
        if (user == null) {
            return "login";
        }
        model.addAttribute("user",user);
        // 判断是否还有库存
        GoodsVo goodsVo = goodsService.findGoodsById(goodsId);
        if (goodsVo.getStockCount() < 1) {
            model.addAttribute("errmsg", RespBeanEnum.EMPTY_STOCK.getMessage());
            return "seckillFail";
        }
        // 判断是否重复抢购
        SeckillOrder seckillOrder = seckillOrderService.getOne(new QueryWrapper<SeckillOrder>()
                .eq("user_id", user.getId())
                .eq("goods_id", goodsId));

        if (seckillOrder != null) {
            model.addAttribute("errmsg",RespBeanEnum.REPEATE_ERROR.getMessage());
            return "seckillFail";
        }
        // 购物
        Order order = orderService.seckill(user,goodsVo);
        model.addAttribute("order", order);
        model.addAttribute("goods", goodsVo);
        return "orderDetail";
    }

}
